package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.project.domain.ConstructionProgress;
import net.hn.hnms.biz.project.mapper.ConstructionPlanMapper;
import net.hn.hnms.biz.project.mapper.ConstructionProgressMapper;
import net.hn.hnms.biz.project.mapper.ProjectFileMapper;
import net.hn.hnms.biz.project.request.ConstructionProgressReq;
import net.hn.hnms.biz.project.service.IConstructionProgressService;
import net.hn.hnms.biz.project.vo.ConstructionProgressVo;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘昊
 * @date 2024-03-18 9:33
 * 施工进度管理
 */
@Service
@Slf4j
public class ConstructionProgressServiceImpl implements IConstructionProgressService {

    @Autowired
    private ConstructionPlanMapper planMapper;
    @Autowired
    private ConstructionProgressMapper progressMapper;

    @Autowired
    private ProjectFileMapper projectFileMapper;

    @Override
    public R<Void> insertReq(ConstructionProgressReq req) {

        ConstructionProgress progressDO = new ConstructionProgress();
        try {
            progressDO.setProjectId(req.getProjectId());
            progressDO.setConstructionId(req.getConstructionId());
            progressDO.setProjectName(req.getProjectName());
            progressDO.setConstructionUnit(req.getConstructionUnit());
            progressDO.setReport(req.getReport());
            progressDO.setReportTime(req.getReportTime());
            progressDO.setReportPath(req.getReportPath());
            progressDO.setReportType(req.getReportType());
            progressDO.setCompanyCode(req.getCompanyCode());
//            progressDO.setMineCode(req.getCompanyCode());
            log.info("施工进度新增========>");
            progressMapper.insert(progressDO);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("新增失败");
        }
        return R.ok("新增成功");

    }

    @Override
    public R<Void> deleteReq(ConstructionProgressReq req) {
        return null;
    }

    @Override
    public R<List<ConstructionProgressVo>> selectDetails(ConstructionProgressReq req) {

        QueryWrapper<ConstructionProgress> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(req.getConstructionId())) {
            wrapper.eq("construction_id",req.getConstructionId());
        }
        if (StringUtils.isNotBlank(req.getProjectName())) {
            wrapper.eq("project_name",req.getProjectName());
        }
        if (StringUtils.isNotBlank(req.getConstructionUnit())) {
            wrapper.eq("construction_unit",req.getConstructionUnit());
        }
        if (StringUtils.isNotBlank(req.getReportType())) {
            wrapper.eq("report_type",req.getReportType());
        }
        log.info("施工进度查询========>");
        List<ConstructionProgressVo> progressVoList = progressMapper.selectList(wrapper).stream().map(item -> {
            ConstructionProgressVo progressVo = new ConstructionProgressVo();
            BeanUtils.copyProperties(item,progressVo);
            return progressVo;
        }).collect(Collectors.toList());

        return R.ok("查询成功",progressVoList);
    }

    @Override
    public R<Void> deleteList(List<String> idList) {
        return null;
    }

    @Override
    public  ResponsePage<ConstructionProgress> selectPageList(ConstructionProgressReq req, PageQuery pageQuery) {

//        QueryWrapper<ConstructionProgress> wrapper = new QueryWrapper<>();
//        QueryWrapper<ConstructionPlan> planQueryWrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(req.getConstructionId())) {
//            planQueryWrapper.eq("construction_id",req.getConstructionId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectId())) {
//            planQueryWrapper.eq("project_id",req.getProjectId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectName())) {
//            planQueryWrapper.eq("project_name",req.getProjectName());
//        }
//        if (StringUtils.isNotBlank(req.getConstructionUnit())) {
//            planQueryWrapper.eq("construction_unit",req.getConstructionUnit());
//        }
//        if (StringUtils.isNotBlank(req.getMineCode())) {
//            planQueryWrapper.eq("mine_code",req.getMineCode());
//        }
//        log.info("施工进度查询========>");
////        List<ConstructionPlan> planList = planMapper.selectList(planQueryWrapper);
////        List<String> projectIds = planList.stream()
////                .map(ConstructionPlan::getConstructionId)
////                .collect(Collectors.toList());
////        wrapper.in("construction_id",projectIds);
//        Page<ConstructionPlan> page = planMapper.selectPage(pageQuery.build(),planQueryWrapper);
//        List<ConstructionProgressVo> resList = page.getRecords().stream()
//                .map(item -> {
//                    ConstructionProgressVo progressVo = new ConstructionProgressVo();
//                    BeanUtils.copyProperties(item,progressVo);
//                    return progressVo;
//                }).collect(Collectors.toList());
//
//        return R.ok("查询完成",new ResponsePage<>(resList, page.getTotal()));
        //先查询项目信息（项目名称和施工单位）
        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
        //提取projectId列表
        List<String> projectIds = projectListByCondition.stream()
                .map(ProjectInfoVo::getProjectId)
                .collect(Collectors.toList());
        req.setProjectIds(projectIds);

        Page<ConstructionProgress> page = progressMapper.selectPage(pageQuery.build(), buildQuery(req).orderByDesc(ConstructionProgress::getCreateTime));

        List<ConstructionProgress> list = page.getRecords().stream().map(o -> {
            ConstructionProgress vo = new ConstructionProgress();
            BeanUtil.copyProperties(o, vo);

            // 获取项目名称和施工单位信息
            Optional<ProjectInfoVo> projectInfo = projectListByCondition.stream()
                    .filter(p -> p.getProjectId().equals(o.getProjectId()))
                    .findFirst();

            projectInfo.ifPresent(p -> {
                vo.setProjectName(p.getProjectName());
                vo.setConstructionUnit(p.getConstructionUnit());
            });

            return vo;
        }).collect(Collectors.toList());
        return new ResponsePage<>(list, page.getTotal());
    }


    private LambdaQueryWrapper<ConstructionProgress> buildQuery(ConstructionProgressReq req){
        return new LambdaQueryWrapper<ConstructionProgress>()
//                .like(StrUtil.isNotBlank(req.getVehicleCode()), ConstructionProgress::getVehicleCode, req.getVehicleCode())
                .in(!CollectionUtils.isEmpty(req.getProjectIds()), ConstructionProgress::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getProjectId()), ConstructionProgress::getProjectId, req.getProjectId())
                .eq(StrUtil.isNotBlank(req.getMineCode()), ConstructionProgress::getMineCode, req.getMineCode());
    }
}
